from django.conf import settings
from django.shortcuts import redirect
from rest_framework import status
from rest_framework.generics import ListAPIView, \
    UpdateAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.headline.models import Channel, Article, Comment
from apps.headline.serializers import ChannelSerializer, \
    ArticleSerializer, CollectedSerializer, \
    ArticlesSerializer, ArticleInfoSerializer, ArticleSearchSerializer
from utils.fastdfs.fastdfs_storage import MyStorage
from utils.paginate import PageNum, PageNumber

# Create your views here.
from apps.questions.models import Label


class ChannelView(ModelViewSet):
    # 频道列表序列化器
    serializer_class = ChannelSerializer
    # 频道数据查询集
    queryset = Channel.objects.all()
    # 分页
    pagination_class = PageNumber


# 显示所有文章
class ArticlesAPIView(ListAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = PageNum


# 页面文章展示
class ArticleAPIView(ListAPIView):
    def get_queryset(self):
        pk = self.kwargs.get('id')
        return Article.objects.filter(channel_id=pk)

    serializer_class = ArticleSerializer
    pagination_class = PageNum


# 收藏
class CollectedAPIView(UpdateAPIView):
    queryset = Article.objects.all()

    serializer_class = CollectedSerializer

    def update(self, request, *args, **kwargs):
        user = request.user
        id = self.kwargs.get('id')
        article = Article.objects.get(id=id)
        users = article.collected_users.all()
        if user in users:
            article.collected_users.remove(user)
            return Response({
                'message': '取消收藏成功',
                'success': True
            },
                status=status.HTTP_200_OK
            )
        else:
            article.collected_users.add(user)
            return Response({
                'message': '收藏成功',
                'success': True
            },
                status=status.HTTP_200_OK
            )


# 根据ID获取文章详情信息
class ArticleInfoAPIView(RetrieveAPIView):

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        return Article.objects.filter(id=pk)

    serializer_class = ArticleInfoSerializer


# class ArticleCreateAPIView(CreateAPIView):
#
#     queryset = Article.objects.all()
#     serializer_class = ArticleCreateSerializer
#
#     def create(self, request, *args, **kwargs):
#
#         user_id = request.user.id
#         request.data['user_id']=user_id
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         self.perform_create(serializer)
#         article_id = Article.objects.get(user_id=user_id)
#
#         return Response({
#             'articleid':article_id,
#             'message': '发表成功',
#             'success': True
#         },
#             status=status.HTTP_200_OK
#         )
#         # return Response(serializer.data,status=status.HTTP_201_CREATED,headers=headers)

# 发布文章
class ArticlePostViewSet(APIView):

    def post(self, request):
        user = request.user
        data = request.data
        article = Article()
        article.user = user
        article.channel = Channel.objects.get(id=data['channel'])
        article.content = data['content']
        article.title = data['title']
        article.image = data.get('image')
        article.save()

        for label_id in data['labels']:
            label = Label.objects.get(id=label_id)
            article.labels.add(label)
        article.save()

        return Response({
            "articleid": article.id,
            "message": "OK",
            "success": True
        })


# 评论文章
class CommentPublishAPIView(APIView):

    # def get_queryset(self):
    #     pk = self.kwargs.get('pk')
    #     return Comment.objects.filter(article_id=pk)
    #
    # serializer_class = CommentsSerializer
    #
    # def create(self, request, *args, **kwargs):
    #     user_id = request.user.id
    #     request.data['user_id'] = user_id
    #     article = Article.objects.get(id=request.data.get('article'))
    #     count = article.comment_count
    #     count += 1
    #     article.comment_count=count
    #     article.save()
    #
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     self.perform_create(serializer)
    #
    #     return Response({
    #         "message": "评论成功",
    #         "success": True
    #     })

    def post(self, request, pk):
        data = request.data
        data['user_id'] = request.user.id
        data.pop('article')
        data['article_id'] = pk

        try:
            parent = data.pop('parent')
            data['parent_id'] = parent
        except Exception:
            pass
        comment = Comment.objects.create(**data)
        comment.article.comment_count += 1
        comment.article.save()

        return Response({
            "message": "评论成功",
            "success": True
        })

# 搜索
class ArticleSearchView(ListAPIView):
    serializer_class = ArticleSearchSerializer

    pagination_class = PageNum

    def list(self, request, *args, **kwargs):
        text = request.GET.get('text')
        queryset = Article.objects.filter(title__contains=text)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data)

class UploadImageView(APIView):

    def post(self,request):
        storage = MyStorage()
        img_url = storage._save('',request.FILES.get('upload'))
        from_address = request.META['HTTP_REFERER']
        from_address = from_address[:from_address.rfind('/'):]
        # result_url = from_address + '/upload_success.html? image_url=' + settings.FDFS_URL + img_url + '4&CKEditorFuncNum=' + request.query_params.get('4&CKEditorFuncNum')
        i = request.query_params.get('CKEditorFuncNum')
        result_url = from_address + '/upload_success.html?image_url=' + settings.FDFS_URL + img_url + '&CKEditorFuncNum=' + str(i)

        return redirect(result_url)